<?php
 
/**
 * 信息维护 ajax类
 * @package  ajax
 * @subpackage  backend
 * @create by allen.qiang
 */
require 'module/base/goodsHandler.class.php';
require 'module/base/promotionHandler.class.php';

class ajax_goodsRecommend {
 
    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //列表
                    $this->goodsRecommendList();
                    break;

                case 2: //新增或编辑
                    $this->goodsRecommendAdd();
                    break;

                case 3: //删除
                    $this->goodsRecommendDel();
                    break;

                case 4: //状态变更
                    $this->changeUseflg();
                    break;

                case 5://根据输入的商品编号得到商品信息
                    $this->getGoodsInfo();
                    break;

            }

        }

    }

    //列表
    public function goodsRecommendList(){

        global $G_PGLOB;

        //实例化商品类
        $goodsHandler = new goodsHandler($G_PGLOB->DBCA);

        //实例化促销类
        $promotionHandler = new promotionHandler( $G_PGLOB->DBCA );

        //查询组合商品
        $result_data = $promotionHandler->searchGoodsRecommend( $_REQUEST );



        //组织返回的数据
        $result_array = array(
            'page' => $_REQUEST['page'],
            'total' => $_REQUEST['count'],
            'rows' => array()
        );

        if ($result_data) {
            foreach($result_data as &$info) {

                //查询主商品信息
                $main_array = array(	'product_code' 	=> $info['product_code']);

                $result_search = $promotionHandler->getGoodsInfo($main_array);
                
                $uid = empty($result_search)? '' : $result_search[0]['postID'];

                $goodsName = empty($result_search)? '' : $result_search[0]['goodsName'];

                $result_array['rows'][] = array(
                    'id' => $info['recom_id'],
                    'cell' => array(
                        '<a href="javascript: void(0);" onclick="goodsRecommend.edit(' . $info['recom_id'] . ')">修改</a>&nbsp;&nbsp;'.
                        '<a href="javascript: void(0);" onclick="goodsRecommend.detail(' . $info['recom_id'] . ')">详情</a>',
                        $info['recom_id'],
                        $info['product_code'],
                        '<font title="' . $goodsName . '"> <a href="/shop/goods-' . $uid . '.html" target="_blank">' . $goodsName . '</a> <font/>',
                        $info['startDate'],
                        $info['endDate'],
                        $info['useFlg'] == 1? '<a href="javascript: void(0);" onclick="goodsRecommend.changeConfirm(' . $info['recom_id'] . ',1)">启用</a>' :
                            '<a href="javascript: void(0);" onclick="goodsRecommend.changeConfirm(' . $info['recom_id'] . ',0)">禁用</a>'
                    )
                );
            }
        }

        echo json_encode($result_array);

    }

    /**
     * 更新或保存
     */
    private function goodsRecommendAdd() {

        global $G_PGLOB;

        $promotionHandler = new promotionHandler($G_PGLOB->DBCA);

        $_REQUEST['operator'] = $G_PGLOB->currentUserID;
        $result_data = $promotionHandler->saveGoodsRecommend($_REQUEST);

        echo json_encode($result_data);

    }

    /**
     * 删除信息
     *
     */
    private function goodsRecommendDel () {

        global $G_PGLOB;

        /**接收参数
         *
         * $_REQUEST[delArr] => Array(
                                    [0] => 19
                                    [1] => 18
                                    [2] => 17
                                    )
         *这是由要删除的recom_id组成的数组
         */
        $delArr = $_REQUEST['delArr'];

        if( empty($delArr) ){

            echo json_encode( array('code'=>400 , 'message'=>'请选择要删除的信息') );
            return ;

        }

        //统计不存在的信息的数目
        $errorNum = 0;

        //记录要删除的entity对象
        $deleteObjArr = array();

        //检查要删除的信息是否全部存在
        foreach( $delArr as $recom_id ){

            //检查信息是否存在
            $check_obj = new entity('promotion_recom');
            $check_obj->recom_id = $recom_id;

            if( !$G_PGLOB->DBCA->fetch( $check_obj ) )
                $errorNum++;

            $deleteObjArr[$recom_id] = $check_obj;

        }

        if( $errorNum > 0 ){

            echo json_encode( array('message'=>'所选部分信息已不存在，请刷新页面' , 'code'=>400 ) );
            return;

        }

        try{

            //开启事务
            $G_PGLOB->DBCA->beginTransaction();

            //循环删除
            foreach( $deleteObjArr as $recom_id=>$delobj ){

                $G_PGLOB->DBCA->delete( $delobj );

                //删除该商品所有的推荐商品
                $delSQL = 'DELETE FROM promotion_recom_detail WHERE recom_id = ?';
                $G_PGLOB->DBCA->stmt_query( $delSQL , 'i' , $recom_id );


            }

            //提交事务
            $G_PGLOB->DBCA->commit();

            echo json_encode( array('message'=>'删除成功', 'code'=>200) );
            return;

        }catch( Exception $e ){

            //回滚事务
            $G_PGLOB->DBCA->rollBack();

            error_log($e->getMessage());
            echo json_encode( array('message'=>'系统错误，请与管理员联系', 'code'=>500) );
            return;

        }

    }

    /**
     * 状态变更
     */
    private function changeUseflg() {

        global $G_PGLOB;

        $recom_id = $_REQUEST['recom_id'];
        $flg      = $_REQUEST['flg'];

        $recom_obj = new entity('promotion_recom');
        $recom_obj->recom_id = $recom_id;

        if( !$G_PGLOB->DBCA->fetch($recom_obj) ){

            echo json_encode( array('message'=>'没有找到信息' , 'code'=>404 ) );
            return;

        }

        $useFlg = $recom_obj->useFlg;

        if( $flg == 1 && $useFlg == 0){
            echo json_encode( array('message'=>'序号['.$recom_id.']信息已处于<b>禁用</b>状态<br>请重新刷新页面' , 'code'=>400 ) );
            return;
        }

        if( $flg == 0 && $useFlg == 1){
            echo json_encode( array('message'=>'序号['.$recom_id.']信息已处于<b>启用</b>状态<br>请重新刷新页面' , 'code'=>400 ) );
            return;
        }

        if( $useFlg == 0 ){
            $recom_obj->useFlg = 1;
        }else{
            $recom_obj->useFlg = 0;
        }

        try{

            $G_PGLOB->DBCA->save( $recom_obj );

            if( $useFlg == 0 ){
                echo json_encode( array('message'=>'已启用' , 'code'=>200 ) );
                return;
            }else{
                echo json_encode( array('message'=>'已禁用' , 'code'=>200 ) );
                return;
            }


        }catch(Exception $e){

            error_log( $e->getMessage() );
            echo json_encode( array('message'=>'系统错误，请与管理员联系' , 'code'=>500 ) );
            return;
        }

    }

    private function getGoodsInfo (){
        global $G_PGLOB;
        //商品编码
        $product_code = isset($_REQUEST['product_code']) ? trim($_REQUEST['product_code']) : '';

        if (empty($product_code)) {
            $result_array = array('code'=>400,'message'=>'请输入商品编号');
            echo json_encode($result_array);
            die();
        }

        //拆散主商品编码，检测是否是三级商品
        //$main = explode( '-' , $_REQUEST['product_code'] );
        //if( count($main) != 3 )
            //die( json_encode( array( 'code'=>400 , 'message'=>'主商品编号只能为三级商品编号' ) ) );

        $goodsHandler = new goodsHandler($G_PGLOB->DBCA);
        $arg_array = array(	
        		'product_code' 	=> $product_code,
                'useFlg'		=> 1,
                'forsale'		=> 1
			);
        $result_search = $goodsHandler->searchGoodsSale( $arg_array );
		
        if (empty($result_search)) {
            $result_array = array('code'=>400,'message'=>'该商品不存在或无库存或已下架');
            echo json_encode($result_array);
            die();
        }

        $result_array = array(	'code'		=> 200 , 'data'	=> $result_search );
        echo json_encode($result_array);
    }


}